package com.fch.sdlibrary.ui.dashboard;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.fch.sdlibrary.BookActivity;
import com.fch.sdlibrary.LoginActivity;
import com.fch.sdlibrary.R;
import com.fch.sdlibrary.entity.BaseResponse;
import com.fch.sdlibrary.entity.Book;
import com.fch.sdlibrary.entity.BookClazz;
import com.fch.sdlibrary.global.MyGlobal;
import com.fch.sdlibrary.util.BookAdapter;
import com.fch.sdlibrary.util.BookClazzAdapter;
import com.fch.sdlibrary.util.PageInfo;
import com.fch.sdlibrary.util.TokenInterceptor;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DashboardFragment extends Fragment {

    private DashboardViewModel dashboardViewModel;
    private Spinner spinner1, spinner2, spinner3;
    private EditText seachBook, seachIsbn;
    private Button seachBookbut, seachIsbnbut;
    private ListView listView;

    private SharedPreferences userInfo;
    private BaseResponse baseResponse;
    private Gson gson = new Gson();
    private List<BookClazz> list1 = new ArrayList<>();
    private List<BookClazz> list2 = new ArrayList<>();
    private List<BookClazz> list3 = new ArrayList<>();

    private List<Book> mData = new ArrayList<>();


    private PageInfo pageInfo = new PageInfo();
    private BookAdapter adapter;
    private Integer pageNum = 1;
    private String PATH = "";


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        dashboardViewModel =
                ViewModelProviders.of(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        init(root);

        send(getContext(), "QueryL1", new MyCallBack(getContext(), list1, spinner1));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Book book = (Book) listView.getAdapter().getItem(i);
                Intent intent = new Intent(getContext(), BookActivity.class);
                intent.putExtra("id", book.getBookId().toString());
                startActivity(intent);
            }
        });

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        pageNum++;
                        seachAddBookMed(getContext(), PATH + "&pageNum=" + pageNum);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        /**
         * 书名搜索按钮
         */
        seachBookbut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (spinner1.getSelectedItem() == null){
                    Toast.makeText(getContext(), "请登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                BookClazz bookCode1 = (BookClazz) spinner1.getSelectedItem();
                BookClazz bookCode2 = (BookClazz) spinner2.getSelectedItem();
                BookClazz bookCode3 = (BookClazz) spinner3.getSelectedItem();

                String searchCode = "-1";
                if (!"-1".equals(bookCode1.getClassCode())) {
                    searchCode = bookCode1.getClassCode();
                }
                if (!"-1".equals(bookCode2.getClassCode())) {
                    searchCode = bookCode2.getClassCode();
                }
                if (!"-1".equals(bookCode3.getClassCode())) {
                    searchCode = bookCode3.getClassCode();
                }

                String searchName = seachBook.getText().toString();
                PATH = "SearchBook?" + "name=" + searchName + "&code=" + searchCode;
                pageNum = 1;
                seachBookMed(getContext(), "SearchBook?" + "name=" + searchName + "&code=" + searchCode);
            }
        });

        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                BookClazz bookClazz = (BookClazz) adapterView.getAdapter().getItem(i);
                spinner2.setAdapter(null);
                spinner3.setAdapter(null);
                send(getContext(), "QueryL2?L1=" + bookClazz.getClassCode(), new MyCallBack(getContext(), list2, spinner2));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                BookClazz bookClazz = (BookClazz) adapterView.getAdapter().getItem(i);
                spinner3.setAdapter(null);
                send(getContext(), "QueryL3?L2=" + bookClazz.getClassCode(), new MyCallBack(getContext(), list3, spinner3));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        return root;
    }

    private void seachAddBookMed(Context context, String path) {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor(context))//拦截器
                .build();//创建Http客户端
        Request request = new Request.Builder()
                .url(MyGlobal.PATH + path)//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                .get()
                .build();//创建Http请求
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功返回结果
                //如果希望返回的是字符串
                final String responseData = response.body().string();
                baseResponse = new BaseResponse<PageInfo>();
                Type type = new TypeToken<BaseResponse<PageInfo>>() {
                }.getType();
                baseResponse = gson.fromJson(responseData, type);
                pageInfo = (PageInfo) baseResponse.getData();
                if (pageInfo.getList().isEmpty())
                    return;
                mData.addAll(pageInfo.getList());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }

    /**
     * 查找图书
     *
     * @param context
     * @param path
     */
    private void seachBookMed(Context context, final String path) {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor(context))//拦截器
                .build();//创建Http客户端
        Request request = new Request.Builder()
                .url(MyGlobal.PATH + path)//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                .get()
                .build();//创建Http请求
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功返回结果
                //如果希望返回的是字符串
                final String responseData = response.body().string();
                baseResponse = new BaseResponse<PageInfo>();
                Type type = new TypeToken<BaseResponse<PageInfo>>() {
                }.getType();
                baseResponse = gson.fromJson(responseData, type);
                pageInfo = (PageInfo) baseResponse.getData();
                if (pageInfo.getList().isEmpty())
                    return;
                mData = pageInfo.getList();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        adapter = new BookAdapter(mData, getLayoutInflater());
                        listView.setAdapter(adapter);
                    }
                });
            }
        });
    }

    /**
     * 查询分类列表
     *
     * @param context
     * @param path
     * @param myCallBack
     */
    private void send(Context context, String path, MyCallBack myCallBack) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .addInterceptor(new TokenInterceptor(context))//拦截器
                .build();//创建Http客户端
        Request request = new Request.Builder()
                .url(MyGlobal.PATH + path)//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                .get()
                .build();//创建Http请求
        Call call = client.newCall(request);
        call.enqueue(myCallBack);
    }

    /**
     * 自定义返回结果
     */
    class MyCallBack implements Callback {

        private Context context;
        private List<BookClazz> bookClazzes;
        private Spinner spinner;

        MyCallBack(Context context, List<BookClazz> bookClazzes, Spinner spinner) {
            this.context = context;
            this.bookClazzes = bookClazzes;
            this.spinner = spinner;
        }

        @Override
        public void onFailure(Call call, IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 更新UI的操作
                    Toast.makeText(getContext(), "链接失败", Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            //请求成功返回结果
            //如果希望返回的是字符串
            final String responseData = response.body().string();

            baseResponse = new BaseResponse<List<BookClazz>>();
            Type type = new TypeToken<BaseResponse<List<BookClazz>>>() {
            }.getType();
            baseResponse = gson.fromJson(responseData, type);
            if (baseResponse.getCode() == 401) {
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {// 更新UI的操作
                        Toast.makeText(getContext(), "请登录", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                if (baseResponse.getData() != null) {
                    bookClazzes = (List<BookClazz>) baseResponse.getData();
                    BookClazz bookClazz = new BookClazz();
                    bookClazz.setClassCode("-1");
                    bookClazz.setClassificationName("请选择分类");
                    bookClazzes.add(0, bookClazz);
                    getActivity().runOnUiThread(new MyRunnable(spinner, bookClazzes));
                }
            }
        }
    }

    /**
     * 自定义修改ui
     */
    class MyRunnable implements Runnable {
        private Spinner spinner;
        private List<BookClazz> bookClazzes;

        MyRunnable(Spinner spinner, List<BookClazz> bookClazzes) {
            this.spinner = spinner;
            this.bookClazzes = bookClazzes;
        }

        @Override
        public void run() {
            spinner.setAdapter(new BookClazzAdapter(bookClazzes, getLayoutInflater()));
        }
    }

    /**
     * 初始化
     *
     * @param root
     */
    private void init(View root) {
        spinner1 = root.findViewById(R.id.spinner1);
        spinner2 = root.findViewById(R.id.spinner2);
        spinner3 = root.findViewById(R.id.spinner3);

        seachBook = root.findViewById(R.id.search_book);
        seachIsbn = root.findViewById(R.id.search_isbn);

        seachBookbut = root.findViewById(R.id.seach_but);
        seachIsbnbut = root.findViewById(R.id.seach_isbn_but);

        listView = root.findViewById(R.id.search_item);
    }
}